package cn.qicaiwang.open.qxyApi.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;

/**
 * IP地址工具类
 */
@Slf4j
public class IpUtils {

    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST_IP = "127.0.0.1";
    private static final String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1";
    private static final int IP_LENGTH = 15;

    // 常见代理服务器请求头
    private static final List<String> PROXY_HEADERS = Arrays.asList(
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_CLIENT_IP",
            "HTTP_X_FORWARDED_FOR",
            "X-Real-IP"
    );

    /**
     * 获取客户端IP地址
     * @param request
     * @return
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = null;

        // 1. 尝试从代理请求头获取
        for (String header : PROXY_HEADERS) {
            ip = request.getHeader(header);
            if (StringUtils.isNotEmpty(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
                break;
            }
        }

        // 2. 如果从代理头获取不到，使用request.getRemoteAddr()
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 3. 处理多级代理情况(取第一个IP)
        if (StringUtils.isNotEmpty(ip) && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }

        // 4. 处理本地地址
        if (LOCALHOST_IP.equals(ip) || LOCALHOST_IPV6.equals(ip)) {
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                log.error("获取本机IP失败", e);
            }
        }

        return StringUtils.isBlank(ip) ? null : ip;
    }

    /**
     *  获取当前请求的客户端IP(简化版)
     * @return
     */
    public static String getClientIp() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes)
                    RequestContextHolder.getRequestAttributes()).getRequest();
            return getClientIp(request);
        } catch (Exception e) {
            log.debug("获取客户端IP失败", e);
            return null;
        }
    }

    /**
     *  获取服务器IP地址
     * @return
     */
    public static String getServerIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.error("获取服务器IP失败", e);
            return null;
        }
    }

    /**
     * 获取服务器主机名
     * @return
     */
    public static String getServerHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            log.error("获取服务器主机名失败", e);
            return null;
        }
    }

    /**
     * 判断是否为内网IP
     * @param ip
     * @return
     */
    public static boolean isInternalIp(String ip) {
        if (StringUtils.isBlank(ip)) {
            return false;
        }

        // 处理IPv6本地地址
        if (LOCALHOST_IPV6.equals(ip)) {
            return true;
        }

        // 处理IPv4地址
        byte[] addr = textToNumericFormatV4(ip);
        if (addr == null) {
            return false;
        }

        // 内网IP段:
        // 10.0.0.0~10.255.255.255
        // 172.16.0.0~172.31.255.255
        // 192.168.0.0~192.168.255.255
        final byte b0 = addr[0];
        final byte b1 = addr[1];

        // 10.x.x.x/8
        if (b0 == (byte) 10) {
            return true;
        }

        // 172.16.x.x/12
        if (b0 == (byte) 172 && b1 >= (byte) 16 && b1 <= (byte) 31) {
            return true;
        }

        // 192.168.x.x/16
        if (b0 == (byte) 192 && b1 == (byte) 168) {
            return true;
        }

        return false;
    }

    /**
     * 将IPv4地址转换为字节数组
     * @param ip
     * @return
     */
    private static byte[] textToNumericFormatV4(String ip) {
        if (ip.length() == 0) {
            return null;
        }

        byte[] bytes = new byte[4];
        String[] elements = ip.split("\\.", -1);
        try {
            long l;
            int i;
            switch (elements.length) {
                case 1:
                    l = Long.parseLong(elements[0]);
                    if ((l < 0L) || (l > 4294967295L)) {
                        return null;
                    }
                    bytes[0] = (byte) (int) (l >> 24 & 0xFF);
                    bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 2:
                    l = Integer.parseInt(elements[0]);
                    if ((l < 0L) || (l > 255L)) {
                        return null;
                    }
                    bytes[0] = (byte) (int) (l & 0xFF);
                    l = Integer.parseInt(elements[1]);
                    if ((l < 0L) || (l > 16777215L)) {
                        return null;
                    }
                    bytes[1] = (byte) (int) (l >> 16 & 0xFF);
                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 3:
                    for (i = 0; i < 2; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L)) {
                            return null;
                        }
                        bytes[i] = (byte) (int) (l & 0xFF);
                    }
                    l = Integer.parseInt(elements[2]);
                    if ((l < 0L) || (l > 65535L)) {
                        return null;
                    }
                    bytes[2] = (byte) (int) (l >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 4:
                    for (i = 0; i < 4; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L)) {
                            return null;
                        }
                        bytes[i] = (byte) (int) (l & 0xFF);
                    }
                    break;
                default:
                    return null;
            }
        } catch (NumberFormatException e) {
            return null;
        }
        return bytes;
    }

    /**
     *  获取IP属地信息(需要集成ip2region等库)
     * @param ip
     * @return
     */
    public static String getIpRegion(String ip) {
        if (StringUtils.isBlank(ip) || isInternalIp(ip)) {
            return "内网IP";
        }

        // 这里可以集成ip2region或其他IP库
        // 示例: return IpRegionUtil.getRegion(ip);
        return "未知";
    }

    /**
     *  验证IP地址格式是否正确
     * @param ip
     * @return
     */
    public static boolean isValidIp(String ip) {
        if (StringUtils.isBlank(ip)) {
            return false;
        }

        // IPv4验证
        String ipv4Pattern = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
        if (ip.matches(ipv4Pattern)) {
            return true;
        }

        // IPv6验证(简化版)
        String ipv6Pattern = "^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$";
        return ip.matches(ipv6Pattern);
    }
}